<template>
<div>
    <div class="e-form">
        <BillTop @cancel="printHandel"></BillTop>
        <div class="tabs warningTabs">
             <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="结算明细" name="changeDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="服务费用" name="recommendedLessor" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="保证金" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="changeHistory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                <div id="baseInfoCon" class="con">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                <!-- 基本信息 -->
                <el-form ref="ruleForm" :model="formData" label-width="160px" :rules="rules">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="结算编号：" >
                           {{formData.billNo}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构：">
                           {{formData.orgName}}
                         </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="业务类型：">
                            <el-select
                                v-model="formData.businessTypeValue"
                                placeholder="请选择"
                                @change="changeBusinessType"
                            >
                                  <el-option
                                  v-for="(
                                    item
                                    ) in businessDtlLists"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="源单编号：">
                        <span>{{formData.sourceNo}}</span>
                        <span class="a"
                        @click="seeSourceOrder">查看</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="结算单位：" prop="settleOrgName">
                            <el-input
                                style="flex: 1"
                                placeholder="选择结算单位"
                                v-model="formData.settleOrgName"
                                disabled>
                                <i
                                slot="suffix"
                                class="el-icon-document-copy"
                                @click="selectSettlementDetails">
                                </i>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结算类型：">
                         {{setSettleType}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="发票号：" prop="invoiceNo">
                            <el-input v-model="formData.invoiceNo" v-enterInteger1>
                                 <span>{{formData.invoiceNo}}</span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="录入人员：">
                          {{formData.inputName}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="不含税金额(元)：" >
                             {{TotalSettlementAmount}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                         <el-form-item label="结算日期：" v-model="formData.settleDate"
                         prop="settleDate">
                            <el-date-picker
                                v-model="formData.settleDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="税率：" prop="taxRate">
                            <el-input placeholder="业务类型对应的源单带入" type='number' class="input-with-select" v-model="formData.taxRate" @change="taxRateEvent">
                                <span>
                                {{formData.taxRate}}
                            </span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="税价合计：">
                            {{totalTaxPrice}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="税额：" prop="taxAmount">
                            <el-input placeholder="业务类型对应的源单带入" class="input-with-select" v-model="formData.taxAmount"
                            type="number"
                            @change="taxAmountEvent"
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="累计结算金额：">
                            {{cumulativeTotalSettlementAmount}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="服务费用(含税)：" >
                                {{TotalSettlementAmountService}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单据来源：">
                          {{ billSourceData }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲预付款金额(元)：">
                              <el-checkbox v-model="checkedBox" @change="isAdvanceChargeAmount"
                              v-if='!formData.isFinalSettle'
                              >
                                   <el-input placeholder=""                               type='number' v-model="formData.advanceChargeAmount" class="input-with-select"
                                   :disabled="checkedBox ? false :true"
                                   @change="advanceChargeAmountHandel"
                                   />
                              </el-checkbox>
                              <el-checkbox v-else disabled v-model="checkedBox">
                                    <span>{{formData.advanceChargeAmount}}</span>
                              </el-checkbox>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="验收编号：">
                          {{ formData.acceptanceNo }}
                        <span class="a"
                        @click="seeAcceptanceNumber">查看</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲个人借支：" >
                            <el-checkbox :disabled="isPersonalBorrowing"
                            v-model="isTickPersonalBorrowing" @change="borrowingEvent"></el-checkbox>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="终期结算：">
                            <el-checkbox v-model="formData.isFinalSettle"
                            @change='finalSettleEvent'></el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲个人借支金额(元)：" >
                            <el-input placeholder=""  v-model="formData.rushPersonalBorrowingAmount" class="input-with-select" :disabled="!isTickPersonalBorrowing" @change="rushPersonalBorrowingAmountEvent">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="币种：">
                          {{formData.currency}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲销对象：" >
                            <!-- 下拉框 -->
                            <el-select
                                v-model="formData.reversalObjectName"
                                placeholder="请选择"
                                @change="changeReversalObject"
                                :disabled="!isTickPersonalBorrowing"
                            >
                                <el-option
                                  v-for="item in reversalObjectList"
                                    :key="item.reversalObjectId"
                                    :label="item.reversalObjectName"
                                    :value="item.reversalObjectId"
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="本位币：">
                            {{ formData.baseCurName}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="本位币汇率：" prop="baseCurRate">
                        <el-input
                        v-model="formData.baseCurRate"
                        type="number"
                        @change="baseCurRateEvent"
                        v-if='isReviseBaseCurRate'
                        >
                        </el-input>
                        <span v-else>
                         {{formData.baseCurRate}}
                        </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="人名币汇率：" >
                            {{formData.rmbRate}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="借支人员：" >
                            <el-input
                                style="flex: 1"
                                placeholder="选择借支人员"
                                v-model="formData.borrower"
                                disabled>
                                <i
                                slot="suffix"
                                class="el-icon-document-copy"
                                @click="onGetSigningName">
                                </i>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结算金额(本位币)：" >
                            {{baseCurAmount}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                     <el-col :span="12">
                        <el-form-item label="状态：" >
                            {{stateLable(formData.state)}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="传输财务共享：">
                            <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.transferFinancialShare)}}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注：">
                            <el-input placeholder="" v-model="formData.remarks" class="input-with-select" type="textarea"
                            :rows="3" maxlength='500'>
                            <span>
                                {{formData.remarks}}
                            </span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                </el-form>
                    </div>
                    </div>
                    <!-- {{webData}} -->
                    <!-- 结算明细 -->
                    <div id="changeDetailCon" class="con">
                        <div class="tabs-title" id="changeDetail">结算明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button size="small" class="btn-greenYellow" @click="selectSettlementDetails">选择明细</el-button>
                                    </div>
                                </div>
                                 <div class="right">
                                    合计：{{TotalSettlementAmount}}
                                </div>
                            </div>
                            <div class="errMessageBox">
                                <p class="errMessage" v-for="(item,index) in detailedErrorList" :key='index'>
                                    {{item}}
                                </p>
                            </div>
                           <div class="e-table">
                            <el-table
                                :data="acceptanceData"
                                border
                                ref="changeDetail"
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                class="table"
                                :default-expand-all='true'
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': acceptanceData, '_this': this, 'ref': 'changeDetail' }"
                            >
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style="cursor: pointer;"
                                            v-if='!row.children'
                                            >
                                                <img src="@/assets/btn/delete.png"  @click="handleDeletePlanList(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="物资类别"
                                    fixed
                                    min-width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    fixed
                                    min-width="150"
                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格"   min-width="150">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质"  min-width="150">
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位"  min-width="150">
                                </el-table-column>
                                <el-table-column
                                    label="未结算数量"
                                    min-width="150"
                                    prop="unsettleQuantity"
                                >
                                </el-table-column>

                                 <el-table-column
                                    label="结算数量"
                                    min-width="150"
                                    prop="quantity"
                                >
                                <template slot-scope="{row}">
                                <el-input v-model="row.quantity" class="input-with-select"
                                type="number"
                                v-if='!row.children'
                                @change="settlementQuantityEvent(row)"
                                >
                                </el-input>
                                <span v-else>{{row.quantity}}</span>
                                </template>
                                </el-table-column>
                                 <!-- acceptPrice 窗口数据名称-->
                                <el-table-column
                                    label="验收单价(元)"
                                    min-width="150"
                                    prop="price"
                                >
                                </el-table-column>

                                <el-table-column
                                    label="结算单价(元)"
                                    min-width="150"
                                    prop="settlePrice"
                                >
                                </el-table-column>

                                <el-table-column
                                    label="结算金额(元)"
                                    min-width="150"
                                    prop="taxExcludedAmount"
                                >
                                <template slot-scope="{row}">
                                <el-input v-model="row.taxExcludedAmount" class="input-with-select"
                                type="number"
                                v-if='!row.children'
                                @change="settlementdAmountEvent(row)"
                                >
                                </el-input>
                                <span v-else>{{row.taxExcludedAmount}}</span>
                                </template>
                                </el-table-column>

                                <el-table-column
                                    label="差额"
                                    min-width="150"
                                    prop="difference"
                                >
                                <template slot-scope="{row}">
                                     <span v-if="!row.children">{{getDifferenceData(row)}}</span>
                                </template>
                                </el-table-column>

                                <el-table-column
                                    label="税额差额"
                                    min-width="200"
                                    prop="taxAmountDifference"
                                >
                                 <template slot-scope="{row}">
                                     <span v-if="!row.children">{{getTaxAmountDifference(row)}}</span>
                                </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        </div>
                    </div>
                    <!-- 服务费用 -->
                    <div id="serviceFyCon" class="con">
                        <div class="tabs-title" id="recommendedLessor">服务费用</div>
                        <div class="e-table" style="background-color: #fff">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" @click="onAddList1">新增行</el-button>
                                        <el-button class="btn-greenYellow" @click="allDeleteService">批量删除</el-button>
                                    </div>
                                </div>
                                <div class="right">
                                    合计：{{TotalSettlementAmountService}}
                                </div>
                            </div>
                            <div class="errMessageBox">
                                        <p class="errMessage" v-for="(item,index) in serviceErrorList" :key='index'>
                                            {{item}}
                                        </p>
                                    </div>
                            <div class="e-tree-table">
                                <el-table
                                    ref="tableDataServiceShowTable"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="id"
                                    :data="tableDataServiceShow"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    @selection-change="changeDataService"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataServiceShow, '_this': this, 'ref': 'tableDataServiceShowTable' }"
                                >
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column
                                        type="selection"
                                        width="55"
                                        fixed
                                    >
                                    </el-table-column>
                                    <el-table-column prop="itemName" label="操作" width="150">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEleService(row)"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="合同编号" min-width="200" prop="contractNumber" show-overflow-tooltip>
                                        <template slot-scope="{ row, $index }">
                                            {{ row.contractNumber }}<i slot="suffix" class="el-icon-document-copy"
                                            style="margin: 0 0 0 5px;" @click="onSelectHetong(row, $index)"></i>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="结算单位" min-width="200" prop="settlementUnitName" show-overflow-tooltip>
                                        <template slot-scope="{ row }">
                                            {{ row.settlementUnitName }}<i slot="suffix" class="el-icon-document-copy"
                                            style="margin: 0 0 0 5px;" @click="onSelectJsUnit(row)"></i>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="发票编号" width="200" prop="invoiceNo" show-overflow-tooltip>
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.invoiceNo"
                                            v-enterInteger1
                                            @blur="invoiceNoBlur(row)"
                                        ></el-input>
                                    </template>
                                    </el-table-column>
                                    <el-table-column label="清单名称" width="150" prop="contractDtlName" show-overflow-tooltip>
                                        <template slot-scope="{ row }">
                                            <el-input v-model="row.contractDtlName"
                                              @blur="detailedListNameBlur"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="数量" width="150" prop="quantity">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat2 v-model="row.quantity"
                                            @change="quantityBlur(row)"
                                            ></el-input>
                                        </template>
                                    </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价(元)"
                                    width="100"
                                >
                                </el-table-column>
                                    <el-table-column label="金额(元)" width="150" prop="amount">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat2 v-model="row.amount" @change="amountBlur(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="税率%" width="150" prop="taxRate">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat2 v-model="row.taxRate" @change="taxRateBlur(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="税额(元)" width="150" prop="taxAmount">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat2 v-model="row.taxAmount"
                                            @change="taxAmountBlur(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="税价合计(元)" width="150" prop="totalAmount"></el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                    <!-- 保证金 -->
                    <div id="bzjCon" class="con">
                        <div class="tabs-title" id="attach">保证金</div>
                        <div class="e-table">
                            <div class="mainTitle"><i class="el-icon-d-arrow-right"></i>暂扣保证金</div>
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" @click="onAddListZk">添加</el-button>
                                        <el-button class="btn-greenYellow" @click="allDeleteBond(1)">批量删除</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <el-table
                                    ref="tableDataBzjShow1Table"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="returnDepositId"
                                    :data="tableDataBzjShow1"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    @selection-change="changeDataWithhold"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataBzjShow1, '_this': this, 'ref': 'tableDataBzjShow1Table' }"
                                >
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column
                                        type="selection"
                                        width="55"
                                        fixed
                                    >
                                    </el-table-column>
                                    <el-table-column prop="itemName" label="操作" width="150" v-if="formData.isSystemGeneration !== 1">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEleBzj(row)"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="名称" min-width="200" prop="returnDepositName" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="暂扣保证金(元)" width="200" prop="amount">
                                        <template slot-scope="{ row }">
                                            <el-input type="number"
                                            v-model="row.amount"
                                            @change="bondAmountEvent(row)"
                                            ></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="截止上期末暂扣保证金(元)" width="250" prop="amountBqm" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="截止本期末暂扣还保证金(元)" width="250" prop="amountSqm">
                                        <template slot-scope="{ row }">
                                            {{setAmountSqm(row)}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="说明" min-width="150" prop="remarks">
                                        <template slot-scope="{ row }">
                                          <el-input placeholder="" v-model="row.remarks" class="input-with-select" type="textarea">
                                          </el-input>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div class="e-table">
                            <div class="mainTitle"><i class="el-icon-d-arrow-right"></i>返还保证金</div>
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" :disabled="!formData.sourceId" @click="onAddListFh">添加</el-button>
                                        <span v-if="!formData.sourceId" style="color: #999;">{{ '请选择源单编号' }}</span>
                                        <el-button class="btn-greenYellow" @click="allDeleteBond(2)">批量删除</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <el-table
                                    ref="tableDataBzjShow2Table"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="returnDepositId"
                                    :data="tableDataBzjShow2"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    @selection-change="changeDataReturn"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataBzjShow2, '_this': this, 'ref': 'tableDataBzjShow2Table' }"
                                >
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column
                                        type="selection"
                                        width="55"
                                        fixed
                                    >
                                    </el-table-column>
                                    <el-table-column prop="itemName" label="操作" width="150" v-if="formData.isSystemGeneration !== 1">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEleBzj(row)"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="名称" min-width="200" prop="returnDepositName" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="返还保证金(元)" width="200" prop="amount">
                                        <template slot-scope="{ row }">
                                            <el-input
                                            type="number"
                                            v-model="row.amount"
                                            @change="bondAmountEvent(row)"
                                            >
                                            </el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="截止上期末未返还保证金(元)" width="250" prop="amountBqm" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="截止本期末未返还保证金(元)" width="250" prop="amountSqm">
                                         <template slot-scope="{ row }">
                                            {{setAmountSqm(row)}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="说明" min-width="150" prop="remarks">
                                          <template slot-scope="{ row }">
                                          <el-input placeholder="" v-model="row.remarks" class="input-with-select" type="textarea">
                                          </el-input>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="changeHistory">附件信息</div>
                        <attach-index :relationId="attachId" bucketName="facilityplan" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType=6095
                                ref="AuditHistoryRef"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
            <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
            <div class="buttons">
                <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>
                <PccExaButtons :auditState="auditState" @exas="exas" :founderId="formData.founderId" :state="formData.state"/>
                <el-button size="small" @click="printHandel">取消</el-button>
            </div>
         </div>
    </div>
</div>

</template>

<script>
import { mapState, mapMutations } from 'vuex'
import '@/utils/jquery.scrollTo.min'
import attachIndex from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import PccExaButtons from '@/components/common/exaButtons.vue'
import request from '@/api/settlementManagement/weeklyMaterialSettlement/purchaseSettlement.js'
//周材公共接口
import publicRequest from '@/api/settlementManagement/publicRequest/publicRequest.js'
// import { openAppClient,selectDataClient, hideLoading, throttle, formatDate,getUuid } from '@/utils/common'
import { hideLoading, throttle, formatDate, getUuid, selectDataClient, openAppClient } from '@/utils/common'
//从物资验收中的服务费用模块引入
import materialRequest from '@/api/materials/materialAcceptance'
export default {
    data () {
        return {
            isFontColor: true,
            fake: true,    //判断changeType的数值  -1 1 2
            redBillStatusStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center',
            },
            auditHistoryTable: [], //审核历史表格
            businessDtlLists: [{         //业务类型
                value: '0',
                label: '物资采购合同',
            }, {
                value: '1',
                label: '临时需用计划'
            }, {
                value: '2',
                label: '调拨单'
            }],
            value: '',
            tabsName: 'baseInfo',
            checkedBox: false, //冲预付款金额勾选参数
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            tableData: [],
            formData: {
                //配置计划基础信息
                'acceptanceNo': '',
                'advanceChargeAmount': 0,
                'baseCurAmount': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'billSource': 0,
                'borrower': '',
                'businessTypeKey': 0,
                'businessTypeValue': '',
                'cumulativeSettleAmount': 0,
                'currency': '',
                'currencyId': '',
                'evaluationGrade': 0,
                'inputId': '',
                'inputName': '',
                'invoiceNo': '',
                'isFinalSettle': 0,
                'isRed': 0,
                'isRushAdvanceCharge': 0,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDesciption': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'parentId': '',
                'redStatus': 0,
                'remarks': '',
                'reversalObjectId': 0,
                'reversalObjectName': 0,
                'rmbAmount': 0,
                'rmbRate': 0,
                'rushPersonalBorrowing': 0,
                'rushPersonalBorrowingAmount': 0,
                'settleDate': formatDate(new Date(), 'yyyy-MM-dd'), //结算日期,
                'settleOrgName': '',
                'settleOrgId': '',
                'settleType': 0,
                'sourceId': '',
                'sourceNo': '',
                'state': 0,
                'taxAmount': 0,
                'taxExcluding': 0,
                'taxRate': 0,
                'totalTaxPrice': 0,
                'transferFinancialShare': 0,
                'transportUnitCost': 0,
                'workId': '',
                'settleAmount': 0
            },
            acceptanceData: [
                {
                    'children': [],
                    'topClassId': '',
                    'topClassName': '',
                    'totalAmount': 0,
                    'totalQuantity': 0,
                    'uuid': '12348asdzxxcuiwi'
                }
            ],                 //选择物资 结算明细
            tableDataBzj: [], // 保证金
            MouseEnterId: 0,
            rules: {
                settleOrgName: [
                    { required: true, message: '请选择结算单位', trigger: 'blur' }
                ],
                settleDate: [
                    { required: true, message: '请选择结算日期', trigger: 'blur' }
                ],
                invoiceNo: [
                    { required: true, message: '请填写发票号', trigger: 'blur' }
                ],
                taxRate: [
                    { required: true, message: '请填写税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请填写税额', trigger: 'blur' }
                ],
                baseCurRate: [
                    { required: true, message: '请填写本位币汇率', trigger: 'blur' }
                ],
                remarks: [
                    { max: 500, message: '长度不超过500个字符', trigger: 'blur' }
                ],
            },
            billId: this.$route.query.billid,
            checkPerson: false,
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 6095,
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 6095,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            billType: 6095,
            oldConfigPlan: [], //从配置计划带过来的数据
            oldLeasePlan: [], //从选择物资带过来的数据
            winEvent: {},
            tableDataService: [], // 服务费用明细
            //获取当前页面可以操作的按钮
            buttonParams: {
                'billId': this.$route.query.billid,
                'billType': 6095, // 对应模块Id
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': ''
            },
            //冲销对象选选择
            reversalObjectList: [],
            isReviseBaseCurRate: true, //本位币汇率是否可以修改
            //结算明细中用于提示错误的数据
            detailedErrorList: [],
            //服务费用中用于提示错误的数据
            serviceErrorList: [],
            //是否禁用冲个人借支
            isPersonalBorrowing: false,
            //是否勾选冲个人借支
            isTickPersonalBorrowing: false,
            //未冲销预付款
            noAdvanceCharge: 0,
            tabArr: [], //用于验证功能列表中的必填项
            serviceSelectList: [], //服务费用选中需要批量删除的数据
            bondWithholdSelectList: [], //暂扣保证金选中需要批量删除的数据
            bondReturnSelectList: [], //返还保证金选中需要批量删除的数据
            webData: '' //页面测试数据
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
        }),
        //根据状态值参数决定是否展示打印按钮
        stateLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value == param)
                return (obj ?  obj.label :  '')
            }
        },
        //传输财务共享
        shareLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        //当前单据状态
        state () {
            return this.formData.state
        },
        //附件信息获取当前billid
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 258 - this.lastConHeight
        },
        //---------------基本信息-----------------//
        //当前单据来源
        billSourceData () {
            const obj = {
                0: '新增',
                1: '验结一体'
            }
            return obj[this.formData.billSource]
        },
        //当前结算类型
        setSettleType () {
            const obj = {
                1: '内部列账',
                2: '外来发票',
            }
            return obj[this.formData.settleType]
        },
        //税价合计
        totalTaxPrice () {
            return (this.TotalSettlementAmount * 1 + this.formData.taxAmount * 1 + this.bondTotalAmount * 1 - ((this.formData.advanceChargeAmount * 1) || 0)).toFixed(2) * 1
        },
        //累计结算金额
        cumulativeTotalSettlementAmount () {
            return  (this.totalTaxPrice + this.TotalSettlementAmountService).toFixed(2) * 1
        },
        //本位币金额
        baseCurAmount () {
            return (this.cumulativeTotalSettlementAmount * (this.formData.baseCurRate || 0)).toFixed(2) * 1
        },
        //-----------------结算明细-----------------------//
        //计算差额
        getDifferenceData () {
            return row=>{
                const target = (Number(row.taxExcludedAmount) || 0) - (Number(row.acceptAmount) || 0)
                row.difference = target.toFixed(2) * 1
                return target.toFixed(2) * 1
            }
        },
        //计算税额差额
        getTaxAmountDifference () {
            return row=>{
                //计算税额
                const taxAmount = ((Number(row.taxExcludedAmount) || 0 ) * (Number(this.formData.taxRate) || 0) / 100).toFixed(2) * 1
                const target = (taxAmount - ( Number(row.acceptTaxAmount) || 0)).toFixed(2) * 1
                row.taxAmountDifference = target
                return target
            }
        },
        //计算结算金额总额
        TotalSettlementAmount () {
            return this.acceptanceData[0].children.reduce((a, b)=>a + (Number(b.taxExcludedAmount) || 0), 0)
        },
        //-----------------服务费用---------------------//
        tableDataServiceShow () {
            return this.tableDataService.filter(item => item.changeType !== -1)
        },
        //税价合计总和
        TotalSettlementAmountService () {
            return this.tableDataServiceShow.reduce((a, b)=>a + (Number(b.totalAmount) || 0), 0)
        },
        //-------------------保证金--------------------//
        tableDataBzjShow1 () {
            return this.tableDataBzj.filter(item => item.changeType !== -1 && item.depositType === 1)
        },
        tableDataBzjShow2 () {
            return this.tableDataBzj.filter(item => item.changeType !== -1 && item.depositType === 2)
        },
        //本期金额总计
        bondTotalAmount () {
            return this.tableDataBzj.reduce((a, b)=>a + (Number(b.amount) || 0), 0)
        },
        //暂扣保证金总计
        bondTotalAmountWithhold () {
            return this.tableDataBzj.filter(item=>item.depositType == 1).reduce((a, b)=>a + (Number(b.amount) || 0), 0)
        },
        //返还保证金总计
        bondTotalAmountReturn () {
            return this.tableDataBzj.filter(item=>item.depositType == 2).reduce((a, b)=>a + (Number(b.amount) || 0), 0)
        }

    },
    components: {
        attachIndex,
        ComAuditHistoryIndex,
        PccExaButtons
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        //获取未冲销预付款
        'formData.sourceId': {
            deep: true,
            async handler (newVal) {
                if(newVal) {
                    const data = await request.getAdvancePayment({ contractId: newVal })
                    if(typeof data == 'object') {
                        if(data.code == 200) {
                            this.noAdvanceCharge = data ? (data.data || 0) : 0
                        }else {
                            this.noAdvanceCharge = 0
                        }
                    }else {
                        this.noAdvanceCharge = data || 0
                    }
                }

            }
        },
        //监听不含税总金额计算总税额
        TotalSettlementAmount: {
            handler (newVal) {
                if(newVal || newVal === 0) {
                    this.formData.taxAmount = (newVal * (this.formData.taxRate / 100)).toFixed(2) * 1
                }
            },
        },
        //监听服务明细表格及时更新冲销对象
        tableDataServiceShow: {
            deep: true,
            handler (newVal) {
                console.log(newVal, 'newVal')
                if(newVal && newVal.length > 0) {
                    //获取单位id和名称
                    const targetId = []
                    newVal.forEach(item=>{
                        if(item.reversalObjectId) {
                            const obj = {
                                reversalObjectId: item.settlementUnitId,
                                reversalObjectName: item.settlementUnitName
                            }
                            targetId.push(obj)
                        }
                    })
                    //合并目标并去重
                    const list = [...this.reversalObjectList, ...targetId]
                    this.reversalObjectList = this.duplicateRemoval(list)
                }
            }
        }
    },
    created () {
        this.formData.inputName = localStorage.getItem('userName')
        this.billId = this.$route.query.billid
        this.userId = localStorage.getItem('userId')
        // this.getPlanList() // 结算明细表格数据
        this.formData.orgId = this.userInfo.orgInfo.orgId
        // const { baseCyByOrgId } = this.userInfo
        // this.formData.baseCurName = baseCyByOrgId.currencyName  //本位币
        // this.formData.baseCurName = baseCyByOrgId.currency
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'changeDetail', 'recommendedLessor', 'attach', 'changeHistory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //去重
        duplicateRemoval (list) {
            if(list && list.length > 0) {
                for (let i = 0; i < list.length; i++) {
                    for (let j = i + 1; j < list.length; j++) {
                        if(list[i].reversalObjectId == list[j].reversalObjectId) {
                            list.splice(j, 1)
                            j--
                        }
                    }
                }
            }
            return list
        },
        //重新赋值并默认保留两位小数
        setDataRetainTwoDecimal (list, dtlId, key, val, decimal = 2) {
            const length = list.length
            for (let i = 0; i < length; i++) {
                if(list[i].dtlId == dtlId) {
                    list[i][key] = (Number(val).toFixed(decimal)) * 1
                    break
                }
            }
        },
        //服务单位批量删除
        batchDelete (list, deleteList, condition) {
            //删除页面数据
            for (let i = 0; i < list.length; i++) {
                for (let j = 0; j < deleteList.length; j++) {
                    //新增数据用id判断
                    if(list[i][condition] == deleteList[j][condition]) {
                        list.splice(i, 1)
                        deleteList.splice(j, 1)
                        i--
                        break
                    }
                }
            }
        },
        //查看源单页面
        seeSourceOrder () {
            const urlObj = {
                '临时需用计划': '/momentNeedPlanShow',
                '物资采购合同': '/ctMaterialApplyShow',
                '调拨单': '/revolveAllocationShow'
            }
            const url = urlObj[this.formData.businessTypeValue]
            const billid = this.formData.sourceId
            openAppClient(
            `${url}?billid=${billid}&isview=true`, `${this.formData.businessTypeValue}`
            )
        },
        //查看验收编号
        seeAcceptanceNumber () {
            openAppClient(
            `/weeklyMaterialAccDetail?billid=${this.formData.acceptanceId}&isview=true`, '查看周材验收'
            )
        },
        // 选择借支人员
        onGetSigningName () {
            selectDataClient({
                SelectServiceToken: '/hr/user/getUserUnderOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({ 'orgId': this.formData.orgId }),    // 接口参数
                Title: '选择借支人员' // 标题
            }).then(val => {
                const res = val[0]
                this.formData.borrower = res.userName
            })
        },
        //初始化数据
        init () {
            Promise.all([
                this.getReversalObject(),
                this.getInfo(),
                this.getDetailed(),
                this.getServiceFee(),
                this.getBond(),
                this.getButtonInfo(),
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取冲销对象
        getReversalObject () {
            request.getReversalObject({ billId: this.billId })
                .then(res=>{
                    if(res.length && res[0] != null && res[0].reversalObjectId != '') {
                        this.reversalObjectList = res
                    }
                })
        },
        //获取基本信息数据查看页面
        getInfo () {
            request.queryBasicInformation({ billId: this.billId }).then(res=>{
                const { baseCyByOrgId } = this.userInfo
                this.checkedBox = res.advanceChargeAmount > 0
                this.isReviseBaseCurRate = res.baseCurRate != '1'
                this.isTickPersonalBorrowing = !!res.rushPersonalBorrowing
                this.formData = { ...res, baseCurName: baseCyByOrgId.currencyName, baseCurId: baseCyByOrgId.currency, isFinalSettle: !!res.isFinalSettle, taxAmount: res.taxAmount || 0 }
                this.isPersonalBorrowing = res.businessTypeKey == 1 ? false : true
            })
        },
        //获取结算明细
        getDetailed () {
            request.getPurchaseSettlementDetailed({ billId: this.billId }).then(res=>{
                if(res.length > 0) {
                    res[0].uuid = getUuid()
                    res[0].children.forEach(item=>{
                        item.uuid = getUuid()
                    })
                    this.acceptanceData = res
                }
            })
        },
        //获取服务费用
        getServiceFee () {
            request.getPurchaseSettlementServiceFee({ billId: this.billId }).then(res=>{
                this.tableDataService = res
            })
        },
        //获取保证金
        getBond () {
            request.getPurchaseSettlementBond({ billId: this.billId, depositType: 1 }).then(res=>{
                this.tableDataBzj = res
            })
        },
        //获取流程状态按钮
        getButtonInfo () {
            //获取当前页面可以操作的按钮
            publicRequest.adoptIdObtainGetButtonsData(this.buttonParams).then(res=>{
                this.auditState = res
            })
        },
        //弹框数据
        getTempData () {
            const temp = [ { 'acceptAmount': 0, 'acceptPrice': 0, 'acceptQantity': null, 'baseCurExchangeRate': null, 'billId': null, 'billNo': null, 'contractId': null, 'contractNo': null, 'currency': null, 'currencyId': null, 'dtlId': null, 'hasSettleQantity': 0, 'id': '1563810629957644290', 'isDetailed': 0, 'materialClassId': null, 'materialClassName': null, 'materialId': null, 'materialName': null, 'notSettleQantity': 0, 'parentId': '0', 'settleOrgId': '1563810629957644290', 'settleOrgName': '云南中岚高创供应链管理有限公司', 'spec': null, 'taxAmount': null, 'taxRate': null, 'texture': null, 'unit': null, 'warehouseId': null, 'warehouseName': null }, { 'acceptAmount': 300, 'acceptPrice': 5, 'acceptQantity': 60, 'baseCurExchangeRate': 1, 'billId': '1566979549635997698', 'billNo': 'JTGCZCYS20220828001', 'contractId': '1563810339380457474', 'contractNo': 'JTGCWZCG012', 'currency': '人民币', 'currencyId': '0', 'dtlId': '', 'hasSettleQantity': 49, 'id': '1567080870045216769', 'isDetailed': 1, 'materialClassId': 'a927249575ee-ba4a-3d4e-bcef-a93d5c45/60784b8a-affb-4421-ae50-7186aa2049f0/5bc16149-5150-4d5c-a123-5be36c1bc94f', 'materialClassName': '周转材料/架料、支撑类/脚手架/附件', 'materialId': '1562352846318006274', 'materialName': '碗口支架', 'notSettleQantity': 11, 'parentId': '1563810629957644290', 'settleOrgId': '1563810629957644290', 'settleOrgName': null, 'spec': 'LG-240', 'taxAmount': null, 'taxRate': 9, 'texture': '碗口支架', 'unit': '根', 'warehouseId': null, 'warehouseName': '项目部仓库', 'acceptTaxAmount': 27, 'changeType': 1, 'unsettleQuantity': 11, 'quantity': 11, 'price': 5, 'sourceDtlId': '1563811545834254337', 'uuid': 'AF81C480-367C-4DA2-9B9A-DA366479F74D', 'difference': -300, 'taxAmountDifference': -27 }, { 'acceptAmount': 0, 'acceptPrice': 0, 'acceptQantity': null, 'baseCurExchangeRate': null, 'billId': null, 'billNo': null, 'contractId': null, 'contractNo': null, 'currency': null, 'currencyId': null, 'dtlId': null, 'hasSettleQantity': 0, 'id': '1564902565166669825', 'isDetailed': 0, 'materialClassId': null, 'materialClassName': null, 'materialId': null, 'materialName': null, 'notSettleQantity': 0, 'parentId': '0', 'settleOrgId': '1564902565166669825', 'settleOrgName': '四川众合基业科技有限公司', 'spec': null, 'taxAmount': null, 'taxRate': null, 'texture': null, 'unit': null, 'warehouseId': null, 'warehouseName': null }, { 'acceptAmount': 400, 'acceptPrice': 20, 'acceptQantity': 20, 'baseCurExchangeRate': 1, 'billId': '1566979549635997698', 'billNo': 'JTGCZCYS20220831001', 'contractId': '1564884044835676162', 'contractNo': 'JTGCWZCG013', 'currency': '人民币', 'currencyId': '0', 'dtlId': '', 'hasSettleQantity': 12, 'id': '1567080872834428930', 'isDetailed': 1, 'materialClassId': 'a927249575ee-ba4a-3d4e-bcef-a93d5c45/d33491b4-e035-407a-a756-63732ed994b8/b6a2d7db-528c-4f7d-ac44-3942d6529bef', 'materialClassName': '周转材料/型材及管材/螺旋钢管', 'materialId': '3c28c8be-1b8b-4af9-9421-8403e13e2643', 'materialName': '螺旋钢管', 'notSettleQantity': 8, 'parentId': '1564902565166669825', 'settleOrgId': '1564902565166669825', 'settleOrgName': null, 'spec': 'Ф820mm*10mm', 'taxAmount': 0, 'taxRate': 50, 'texture': '31号螺旋钢管', 'unit': 't', 'warehouseId': '1555865364495790081', 'warehouseName': '项目部仓库', 'acceptTaxAmount': 200, 'changeType': 1, 'unsettleQuantity': 8, 'quantity': 0, 'price': 20, 'sourceDtlId': '1564912074408783873', 'uuid': '7F1855DF-0961-406C-B7D7-CCC608795539', 'difference': -400, 'taxAmountDifference': -200, 'settlePrice': 0 }, { 'acceptAmount': 60, 'acceptPrice': 6, 'acceptQantity': 10, 'baseCurExchangeRate': 1, 'billId': '1566979549635997698', 'billNo': 'JTGCZCYS20220831001', 'contractId': '1564884044835676162', 'contractNo': 'JTGCWZCG013', 'currency': '人民币', 'currencyId': '0', 'dtlId': '', 'hasSettleQantity': 5, 'id': '1567080872834428931', 'isDetailed': 1, 'materialClassId': 'a927249575ee-ba4a-3d4e-bcef-a93d5c45/a997201ed117-a448-694e-3405-806062d4/a9972033ea25-9428-7244-9460-05336df0', 'materialClassName': '周转材料/其他类/汽车衡', 'materialId': 'a99720926472-9ca2-bb41-b818-180c7952', 'materialName': '汽车衡', 'notSettleQantity': 5, 'parentId': '1564902565166669825', 'settleOrgId': '1564902565166669825', 'settleOrgName': null, 'spec': '', 'taxAmount': 0, 'taxRate': 50, 'texture': '31号汽车衡', 'unit': '台', 'warehouseId': '1555865364495790081', 'warehouseName': '项目部仓库', 'acceptTaxAmount': 30, 'changeType': 1, 'unsettleQuantity': 5, 'quantity': '53', 'price': 6, 'sourceDtlId': '1564912074408783874', 'uuid': '2BECE3D7-543A-4D6D-919E-0F9C35E4F8F4', 'difference': -60, 'taxAmountDifference': -30 } ]
            return temp
        },
        //查看冲销对象中是否有当前新增数据
        iSiTrequiredAdd (targetId, targetName) {
            const list = this.reversalObjectList
            //是否需要新增 false 不要 ture 要
            let isAdd = true
            for (const key in list) {
                //已存在直接退出
                if(list[key].reversalObjectId == targetId) {
                    isAdd = false
                    break
                }
            }
            if(isAdd) {
                const obj = {
                    reversalObjectId: targetId || '',
                    reversalObjectName: targetName || ''
                }
                this.reversalObjectList.push(obj)
            }
        },
        //弹框选择结算明细
        selectSettlementDetails () {
            // const temp = this.getTempData()
            // console.log(temp, 'temp')
            // const father = temp.filter(item=>item.parentId == '0')
            // const target = temp.filter(item=>item.parentId != '0')
            // this.setAcceptanceDataTable(target, father[0])
            selectDataClient({
                SelectServiceToken: '/turnover/acceptance/selectSettleDtl', // 获取选择结算明细
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    'businessTypeKey': Number(this.formData.businessTypeKey),
                    'keyWord': '',
                    'parentId': '0'
                }),
                Title: '选择结算明细' // 标题
            }).then(res => {
                //除去父级
                // this.webData = res
                const father = res.filter(item=>item.parentId == '0')
                const target = res.filter(item=>item.parentId != '0')
                this.setAcceptanceDataTable(target, father[0])
            })
        },
        //处理结算明细数据 tps
        setAcceptanceDataTable (list, father) {
            const subjectList =  this.acceptanceData[0].children
            const subLength = subjectList.length
            const length = list.length
            const targetList = []
            for (let i = 0; i < length; i++) {
                let isRepeat = false
                for (let j = 0; j < subLength; j++) {
                    //找到说明有重复
                    if(list[i].dtlId == subjectList[j].sourceDtlId) {
                        isRepeat = true
                        break
                    }
                }
                //没有就新增
                if(!isRepeat) {
                    const item = list[i]
                    const obj = {
                        settleOrgName: item.settleOrgName || (father ? father.settleOrgName : ''),
                        settleOrgId: item.settleOrgId || (father ? father.settleOrgId : ''),
                        sourceId: item.contractId,
                        sourceNo: item.contractNo,
                        acceptanceId: item.billId,
                        acceptanceNo: item.billNo,
                        currencyId: item.currencyId,
                        currency: item.currency,
                        baseCurRate: item.baseCurExchangeRate,
                        taxRate: item.taxRate
                    }
                    //计算验收的税额=验收金额*验收税率
                    item.acceptTaxAmount = ((Number(item.acceptAmount) || 0) * (Number( item.taxRate) || 0) / 100).toFixed(2) * 1
                    item.changeType = 1
                    item.unsettleQuantity = item.notSettleQantity
                    item.quantity = item.notSettleQantity
                    item.price = item.acceptPrice
                    item.sourceDtlId = item.dtlId
                    item.dtlId = ''
                    item.billId = this.billId
                    item.uuid = getUuid()
                    targetList.push(item)
                    this.isReviseBaseCurRate = obj.baseCurRate != '1'
                    this.formData = { ...this.formData, ...obj }
                }
            }
            //处理明细的冲销对象数据
            this.iSiTrequiredAdd ( this.formData.settleOrgId, this.formData.settleOrgName)
            this.acceptanceData[0].children.push(...targetList)
        },
        //删除单条结算明细数据
        handleDeletePlanList (row) {
            this.acceptanceData[0].children.forEach((item, index)=>{
                if(item.sourceDtlId == row.sourceDtlId) {
                    this.clientPop(
                        'info',
                        '是否删除数据？',
                        ()=>{
                            //如果当前选中的是新增数据只需要把从数组中删除即可
                            if(row.changeType != 1) {
                                const copy = JSON.parse(JSON.stringify(this.acceptanceData[0].children[index]))
                                copy.changeType = -1
                                const paramList = [
                                    {
                                        'children': [copy],
                                        'topClassId': '',
                                        'topClassName': '',
                                        'totalAmount': 0,
                                        'totalQuantity': 0,
                                    }
                                ]
                                request.updetePurchaseSettlementDetailed(paramList)
                            }
                            this.acceptanceData[0].children.splice(index, 1)
                            if(this.acceptanceData[0].children.length == 0) {
                                this.acceptanceData = [
                                    {
                                        'children': [],
                                        'topClassId': '',
                                        'topClassName': '',
                                        'totalAmount': 0,
                                        'totalQuantity': 0,
                                        'uuid': getUuid()
                                    }
                                ]
                            }
                            return
                        }
                    )
                }
            })
        },
        //结算明细-结算数量验证
        settlementQuantityEvent (row) {
            //不可大于未结算数量
            if(row.quantity > row.unsettleQuantity) {
                this.$message.error(`结算数量不可大于未结算数量,当前未结算数量为${row.unsettleQuantity}`)
                row.quantity = row.unsettleQuantity
            }
            this.getSettlePrice(row)
        },
        //结算明细-结算单价
        getSettlePrice (row) {
            let target = 0
            if(row.quantity && row.taxExcludedAmount) {
                target = row.taxExcludedAmount / row.quantity
            }
            row.settlePrice = target.toFixed(2) * 1
        },
        //结算明细-结算金额
        settlementdAmountEvent (row) {
            if(row.taxExcludedAmount < 0) {
                this.$message.error('结算金额不能小于0')
                row.taxExcludedAmount = 0
            }
            row.taxExcludedAmount = Number(row.taxExcludedAmount).toFixed(2) * 1
            this.getSettlePrice(row)
        },
        //终期结算事件
        finalSettleEvent (val) {
            if(val) {
                this.clientPop(
                    'info',
                    '是否终期结算，终期结算后不能再对结算单位进行结算',
                    //确定
                    ()=>{
                        //终期结算时需要将所有预付款进行结算
                        this.checkedBox = true
                        this.formData.advanceChargeAmount = this.noAdvanceCharge || 0
                    },
                    null,
                    //取消
                    ()=>{
                        this.checkedBox = false
                        this.formData.advanceChargeAmount = 0
                        this.formData.isFinalSettle = false
                    }
                )
            }else {
                this.checkedBox = false
                this.formData.advanceChargeAmount = 0
            }
        },
        //业务类型切换事件
        changeBusinessType (val) {
            if(val == '1') {
                this.isPersonalBorrowing = false
            }else {
                this.isPersonalBorrowing = true
                this.isTickPersonalBorrowing = false
                this.formData.rushPersonalBorrowingAmount =  ''
                this.formData.reversalObjectName = ''
            }
            if(val == '2') {
                this.formData.settleType = 1
            }else {
                this.formData.settleType = 2
            }
            //业务类型
            const type = {
                '0': '物资采购合同',
                '1': '临时需用计划',
                '2': '调拨单'
            }
            this.formData.businessTypeKey = Number(val)
            this.formData.businessTypeValue = type[val]
            this.formData.settleOrgName = ''
            this.formData.sourceId = ''
            this.acceptanceData = [
                {
                    'children': [],
                    'topClassId': '',
                    'topClassName': '',
                    'totalAmount': 0,
                    'totalQuantity': 0,
                    'uuid': getUuid()
                }
            ]
            //初始化冲销对象
            this.reversalObjectList = []
        },
        //冲个人借支事件
        borrowingEvent (val) {
            if(val) {
                this.clientPop(
                    'info',
                    '确认冲个人借支？',
                    () => {
                        this.isTickPersonalBorrowing = true
                    },
                    null,
                    ()=>{
                        this.isTickPersonalBorrowing = false
                    }
                )
            }else {
                this.formData.rushPersonalBorrowingAmount = ''
                this.formData.reversalObjectName = ''
            }
        },
        //冲个人借支金额事件
        rushPersonalBorrowingAmountEvent (val) {
            if(val > (this.totalTaxPrice || 0)) {
                this.$message.error('冲个人借支金额不可大于税价合计')
                this.formData.rushPersonalBorrowingAmount = this.totalTaxPrice || '0'
            }
        },
        //冲销对象事件
        changeReversalObject (val) {
            this.formData.reversalObjectId = val
            let obj = {}
            obj = this.reversalObjectList.find(item=>{
                return item.reversalObjectId === val
            })
            this.formData.reversalObjectName = obj.reversalObjectName
        },
        //是否勾选冲预付款
        async isAdvanceChargeAmount (val) {
            if(val) {
                //剩余未冲销预付款如果为0则禁用冲预付款功能
                const isNo = this.noAdvanceCharge == 0
                this.checkedBox = isNo ? false : true
                if(isNo) {
                    this.$message.warning('未冲销预付款金额为0不需要进行冲预付款操作')
                    return
                }
                this.formData.advanceChargeAmount = this.noAdvanceCharge
            }else {
                this.formData.advanceChargeAmount = 0
            }
        },
        //冲预付款事件
        advanceChargeAmountHandel (val) {
            //修改的值必须大于0小于等于未冲销预付款金额
            if(val <= 0 || val > this.noAdvanceCharge) {
                this.formData.advanceChargeAmount = this.noAdvanceCharge
                this.$message.error('冲预付款金额必须大于0并且小于等于未冲销预付款金额')
            }
        },
        //本位币汇率事件
        baseCurRateEvent (val) {
            if (val <= 0) {
                this.$message.error('本位币汇率必须大于0')
                this.formData.baseCurRate = 1
            } else {
                this.formData.baseCurRate = (val * 1).toFixed(4) * 1
            }
        },
        //税率事件
        taxRateEvent (val) {
            if(val < 0 || val > 100) {
                this.$message.error('税率的有效值为0~100')
                this.formData.taxRate = 0
            } else {
                this.formData.taxRate = Number(val).toFixed(2) * 1
            }
            this.formData.taxAmount = (this.TotalSettlementAmount * (this.formData.taxRate / 100)).toFixed(2) * 1
        },
        // 服务费用 选择物资采购合同
        async onSelectHetong (row, index) {
            // 物资验收-服务费用:选择合同
            const contracted = {
                contractId: row.contractId,
                contractType: 2
            }
            const res = await materialRequest.getContract(
                { orgid: this.formData.orgId, contractId: this.formData.sourceId },
                contracted
            )
            let result
            // 如果选择的是合同并且合同下有清单,则需带入合同下的清单
            if (res.list && res.list.length > 0) {
                result = res.list.map(item => {
                    return {
                        amount: null,
                        billId: this.billId,
                        changeType: 1,
                        contractId: res.contractId,
                        contractNumber: res.contractNumber,
                        contractDtlId: item.detailedId,
                        contractDtlName: item.name,
                        contractQuantity: item.quantity, // 这个字段是用于在修改数量时,不能大于合同数量的
                        dtlId: '',
                        invoiceNo: '',
                        price: null,
                        quantity: item.quantity,
                        settlementUnitId: res.secondPartyId,
                        settlementUnitName: res.secondPartyName,
                        taxAmount: 0,
                        taxRate: res.taxRate,
                        totalAmount: 0
                    }
                })
                let _arr = []
                result.forEach(item => {
                    const shouldPush = this.tableDataService.every(
                        it => item.contractDtlId !== it.contractDtlId
                    )
                    if (shouldPush) {
                        _arr.push(item)
                    } else {
                        // 找到了清单ID相同
                        const repeatArr = this.tableDataService.filter(
                            i => item.contractDtlId === i.contractDtlId
                        )
                        const noPush = repeatArr.some(
                            _its => _its.changeType !== -1
                        )
                        if (!noPush) {
                            _arr.push(item)
                        }
                    }
                })
                if (_arr.length !== 0) {
                    this.tableDataService.splice(index, 1, ..._arr)
                }
            } else {
                // 如果选择的合同没有清单
                result = {
                    amount: null,
                    billId: this.billid,
                    changeType: 1,
                    contractBillId: res.contractId,
                    contractBillNo: res.contractNumber,
                    contractBillType: res.contractType,
                    contractDtlId: '',
                    contractDtlName: '',
                    dtlId: '',
                    invoiceNo: '',
                    price: null,
                    quantity: null,
                    settlementUnitId: res.secondPartyId,
                    settlementUnitName: res.secondPartyName,
                    taxAmount: 0,
                    taxRate: res.taxRate,
                    totalAmount: 0
                }
                const shouldPush = this.tableDataService.every(
                    it => it.contractBillId !== result.contractBillId
                )
                if (shouldPush) {
                    this.tableDataService.splice(index, 1, result)
                } else {
                    const repeatArr = this.tableDataService.filter(
                        i => i.contractBillId === result.contractBillId
                    )
                    const noPush = repeatArr.some(
                        _its => _its.changeType !== -1
                    )
                    if (!noPush) {
                        this.tableDataService.splice(index, 1, result)
                    }
                }
            }
        },
        // 服务费用 选择结算单位
        onSelectJsUnit (row) {
            const params = {
                businessUnitTypes: [],
                keyword: '',
                limit: 10,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: [0, 1, 2, 3],
                supplierTypes: [],
                subcontractorTypes: [],
                businessTypes: []
            }
            // params.orgId = this.formData.orgId
            selectDataClient({
                SelectServiceToken: 'GeneralSelectOuter', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                // [row.settlementUnitId]
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[]) // 这个是客户端给的,没有则为空
                InitParamsStr: JSON.stringify(params), // 接口参数(name为模拟参数)
                Title: '选择结算单位' // 标题
            }).then(val => {
                row.settlementUnitId = val[0].outerId
                row.settlementUnitName = val[0].outerName
            })
        },
        // 新增按钮 服务费用
        async onAddList1 () {
            if(this.acceptanceData[0].children.length > 0) {
                this.tableDataService.push({
                    id: getUuid(),
                    'amount': null,
                    'billId': this.billId,
                    'changeType': 1,
                    'contractBillId': '',
                    'contractDtlName': '',
                    'contractId': '',
                    'contractNumber': '',
                    'dtlId': '',
                    'invoiceNo': '',
                    'price': null,
                    'quantity': null,
                    'settlementUnitId': '',
                    'settlementUnitName': '',
                    'taxAmount': 0,
                    'taxRate': 0,
                    'totalAmount': 0
                })
            }else {
                this.$message.warning('请先选择结算明细,才能新增服务费用')
            }
        },
        // 删除服务费用
        deleteEleService (row) {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作',
                () => {
                    //新增直接从数组中删除
                    if(row.changeType == 1) {
                        this.tableDataService = this.tableDataService.filter(item=>item.id != row.id)
                    }else {
                        const target = this.tableDataService.filter(item=>item.dtlId == row.dtlId)
                        this.tableDataService = this.tableDataService.filter(item=>item.dtlId != row.dtlId)
                        target[0].changeType = -1
                        request.updetePurchaseSettlementServiceCharge(target)
                    }
                    //删除冲销对象中的单位
                    const target = this.reversalObjectList
                    for (const key in target) {
                        if(target[key].reversalObjectId == row.settlementUnitId) {
                            this.reversalObjectList.splice(key, 1)
                            if(this.formData.reversalObjectName == row.settlementUnitName) {
                                this.formData.reversalObjectName = ''
                            }
                            break
                        }
                    }
                }
            )
        },
        //服务费用已选中数据
        changeDataService (val) {
            this.serviceSelectList = val
        },
        // 服务费用批量删除
        allDeleteService () {
            const targetLength = this.serviceSelectList.length
            if(targetLength > 0) {
                this.clientPop(
                    'info',
                    `已选择${targetLength}条数据，确定要删除吗？数据删除后不可恢复，请谨慎操作！`,
                    () => {
                        //找出已存在数据
                        const alreadyDataList = this.serviceSelectList.filter(item=>item.changeType != 1)
                        //找出新增数据
                        const addDataList = this.serviceSelectList.filter(item=>item.changeType == 1)
                        if(addDataList.length > 0) {
                            this.batchDelete(this.tableDataService, addDataList, 'id')
                        }
                        if(alreadyDataList.length > 0) {
                            alreadyDataList.forEach(item=>{
                                item.changeType = -1
                            })
                            request.updetePurchaseSettlementServiceCharge(alreadyDataList)
                            this.batchDelete(this.tableDataService, alreadyDataList, 'dtlId')
                        }
                    }
                )
            }else {
                this.$message.warning('请至少选择一条数据')
            }
        },
        //服务费用 清单名称
        detailedListNameBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        //服务费用 发票编号
        invoiceNoBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        //服务费用 数量
        quantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // // 不能超过合同数量
            if (row.contractQuantity) {
                if (row.quantity > row.contractQuantity) {
                    this.clientPop(
                        'err',
                        `不能超过合同数量${row.contractQuantity}`
                    )
                    row.quantity = row.contractQuantity
                }
            }
            if (+row.amount && +row.quantity) {
                row.price = (row.amount / row.quantity).toFixed(4) * 1
            }else {
                row.price = 0
            }
        },
        //服务费用 金额
        amountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            //计算单价
            if (+row.amount && +row.quantity) {
                row.price = (+row.amount / +row.quantity).toFixed(2) * 1
            }else {
                row.price = 0
            }
            //计算税额
            row.taxAmount = ((Number(row.amount) || 0) * (row.taxRate ? row.taxRate / 100 : 0)).toFixed(2) * 1
            //计算税价合计
            row.totalAmount = ((Number(row.amount) || 0) + (Number(row.taxAmount) || 0)).toFixed(2) * 1
        },
        //服务费用 税率
        taxRateBlur (row) {
            if(row.taxRate > 100 || row.taxRate < 0) {
                row.taxRate = 0
                this.$message.error('税率有效范围为0~100')
            }
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            //计算税额
            row.taxAmount = ((Number(row.amount) || 0) * (row.taxRate ? row.taxRate / 100 : 0)).toFixed(2) * 1
            //计算税价合计
            row.totalAmount = ((Number(row.amount) || 0) + (Number(row.taxAmount) || 0)).toFixed(2) * 1
        },
        //服务费用 税额
        taxAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            //计算税价合计
            row.totalAmount = ((Number(row.amount) || 0) + (Number(row.taxAmount) || 0)).toFixed(2) * 1
        },
        // 选择暂扣保证金
        onAddListZk () {
            // const val = [{ 'deductionRatio': 0.05, 'depositId': '1523870830363680770', 'depositName': '其他保证金', 'prevTotalAmount': 245 }, { 'deductionRatio': 0.05, 'depositId': '1523870830116216833', 'depositName': '安全保证金', 'prevTotalAmount': 347 }, { 'deductionRatio': 0.05, 'depositId': '1523870830267211777', 'depositName': '民工工资保证金', 'prevTotalAmount': 481 }, { 'deductionRatio': 0.05, 'depositId': '1523870829990387714', 'depositName': '质量保证金', 'prevTotalAmount': 544 }]
            // this.setListBZJ(val, 1)

            selectDataClient({
                SelectServiceToken: '/turnoversettle/Api/getWithholdDeposit',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify(String(this.billType)),
                Title: '选择暂扣保证金' // 标题
            }).then(val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果')
                this.setListBZJ(val, 1)
            })
        },
        // 选择返还保证金
        onAddListFh () {
            // const val = [{ 'deductionRatio': 0.14, 'depositId': '1523870830363687495', 'depositName': '其他保证金', 'prevTotalAmount': 85 }, { 'deductionRatio': 0.24, 'depositId': '1523870830116217496', 'depositName': '安全保证金', 'prevTotalAmount': 96 }, { 'deductionRatio': 0.37, 'depositId': '1523870830267217497', 'depositName': '民工工资保证金', 'prevTotalAmount': 14 }, { 'deductionRatio': 0.18, 'depositId': '1523870829990387498', 'depositName': '质量保证金', 'prevTotalAmount': 32 }]
            // this.setListBZJ(val, 2)

            selectDataClient({
                SelectServiceToken: '/turnoversettle/Api/getReturnDeposit',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    'billType': this.billType,
                    'sourceId': this.formData.sourceId
                }),
                Title: '选择返还保证金' // 标题
            }).then(val => {
                this.setListBZJ(val, 2)
            })
        },
        // 暂扣|返还保证金金额事件
        bondAmountEvent (row) {
            //返还保证金
            if(row.amount < 0) {
                row.amount = 0
                this.$message.error('保证金金额不可为负数')
                return
            }
            if(row.depositType == 2) {
                if(this.bondTotalAmountReturn <= this.bondTotalAmountWithhold) {
                    if(row.amount > row.amountBqm) {
                        row.amount = row.amountBqm
                        this.$message.error('返还保证金金额不可超截止上期末未返还保证金')
                    }
                }else {
                    row.amount = 0
                    this.$message.error('返还保证金总计不可超过暂扣保证金总计')
                }
            }
            row.amount = (Number(row.amount).toFixed(2)) * 1
        },
        // 暂扣|返还保证金截止本期末金额
        setAmountSqm (row) {
            if(row.depositType == 1) {
                row.amountSqm =  (Number(row.amount) || 0) + (Number(row.amountBqm) || 0)
            }else {
                row.amountSqm = (Number(row.amountBqm) || 0) - (Number(row.amount) || 0)
            }
        },
        //暂扣保证金选中项
        changeDataWithhold (val) {
            this.bondWithholdSelectList = val
        },
        //返还保证金选中项
        changeDataReturn (val) {
            this.bondReturnSelectList = val
        },
        //批量删除保证金
        allDeleteBond (type) {
            const list = type == 1 ? this.bondWithholdSelectList : this.bondReturnSelectList
            const targetLength = list.length
            if(targetLength > 0) {
                this.clientPop(
                    'info',
                    `已选择${targetLength}条数据，确定要删除吗？数据删除后不可恢复，请谨慎操作！`,
                    () => {
                        //找出已存在数据
                        const alreadyDataList = list.filter(item=>item.changeType != 1)
                        //找出新增数据
                        const addDataList = list.filter(item=>item.changeType == 1)
                        if(addDataList.length > 0) {
                            this.batchDelete(this.tableDataBzj, addDataList, 'returnDepositId')
                        }
                        if(alreadyDataList.length > 0) {
                            alreadyDataList.forEach(item=>{
                                item.changeType = -1
                            })
                            request.updetePurchaseSettlementBond(alreadyDataList)
                            this.batchDelete(this.tableDataBzj, alreadyDataList, 'returnDepositId')
                        }
                    }
                )
            }else {
                this.$message.warning('请至少选择一条数据')
            }
        },
        //处理保证参数
        setListBZJ (list, depositType) {
            const bjzLength = this.tableDataBzj.length
            const length = list.length
            for (let i = 0; i < length; i++) {
                let isRepeat = false
                for (let j = 0; j < bjzLength; j++) {
                    if(this.tableDataBzj[j].returnDepositId == list[i].depositId) {
                        isRepeat = true
                        break
                    }
                }
                //没有则新增
                if(!isRepeat) {
                    const obj = {
                        'amount': 0,
                        'amountBqm': list[i].prevTotalAmount, //上期末
                        'amountSqm': 0, // 本期末
                        'billId': this.billId,
                        'changeType': 1,
                        'depositType': depositType,
                        'dtlId': '',
                        'remarks': '',
                        'returnDepositId': list[i].depositId,
                        'returnDepositName': list[i].depositName
                    }
                    this.tableDataBzj.push(obj)
                }
            }
        },
        // 删除暂扣保证金、返还保证金
        deleteEleBzj (row) {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                ()=>{
                    if(row.changeType == 1) {
                        this.tableDataBzj = this.tableDataBzj.filter(item=>item.returnDepositId != row.returnDepositId)
                    }else {
                        const target = this.tableDataBzj.filter(item=>item.returnDepositId == row.returnDepositId)
                        this.tableDataBzj = this.tableDataBzj.filter(item=>item.returnDepositId != row.returnDepositId)
                        target[0].changeType = -1
                        request.updetePurchaseSettlementBond(target)
                    }
                }
            )
        },
        //按钮事件
        async exas (arg) {
            if (arg === 'submitCommit') {
                this.saveAll('submitCommit')  //保存并提交
            } else if (arg === 'submit') {
                this.saveAll('submit')   //保存
            } else if (arg === 'deleteData') {
                this.deleteData() //删除
            }
        },
        //税额事件
        taxAmountEvent (val) {
            const target = val ? Number(val).toFixed(2) * 1 : 0
            this.formData.taxAmount = target
        },
        //处理明细参数并返回保存参数
        setParams () {
            const paramsList = []
            //保存基本信息
            const obj = {
                taxExcluding: this.TotalSettlementAmount,
                isFinalSettle: this.formData.isFinalSettle ? 1 : 0,
                isRushAdvanceCharge: this.checkedBox ? 1 : 0,
                rushPersonalBorrowing: this.isTickPersonalBorrowing ? 1 : 0,
                totalTaxPrice: this.totalTaxPrice,
                transportUnitCost: this.TotalSettlementAmountService,
                cumulativeSettleAmount: this.cumulativeTotalSettlementAmount,
                baseCurAmount: this.baseCurAmount,
            }
            Object.assign(this.formData, obj)
            paramsList.push(request.preservePurchaseSettlement(this.formData))
            //更新结算明细
            this.acceptanceData[0].children.forEach(item=>{
                if(item.changeType == 1) {
                    item.dtlId = '' // 传给后端时需要把此id清空用于后端重新添加唯一id号
                }else {
                    item.changeType = 2
                }
            })
            paramsList.push(request.updetePurchaseSettlementDetailed(this.acceptanceData))
            //更新服务费用
            this.tableDataService.forEach(item=>{
                if(item.changeType != 1) {
                    item.changeType = 2
                }
            })
            paramsList.push(request.updetePurchaseSettlementServiceCharge(this.tableDataService))
            //更新保证金
            this.tableDataBzj.forEach(item=>{
                if(item.changeType != 1) {
                    item.changeType = 2
                }
            })
            paramsList.push(request.updetePurchaseSettlementBond(this.tableDataBzj))
            return paramsList
        },
        //保存
        async saveAll (param) {
            //保存不需要进行验证
            if(param == 'submit') {
                this.setParmes()
                return
            }
            //判断合同是否在审核中
            const isType = await request.checkIsChange({ sourceId: this.formData.sourceId, type: String(this.formData.businessTypeKey) })
            if(isType.code && isType.code == 500) {
                return
            }
            console.log(isType, 'isType')
            //保存并提交需要验证是否存在剩余预付款金额没有勾选并且存在剩余预付款金额
            if(!this.checkedBox && this.noAdvanceCharge > 0) {
                this.clientPop(
                    'info',
                    `剩余${this.noAdvanceCharge}预付款还未冲销，是否冲预付款？`,
                    //确定
                    ()=>{
                        this.checkedBox = true
                    },
                    null,
                    //取消
                    ()=>{
                        this.setParmesOrStorage ()
                    }
                )
            }else {
                this.setParmesOrStorage ()
            }
        },
        //处理参数后保存
        setParmes () {
            const paramsList = this.setParams ()
            Promise.all(paramsList)
                .then(()=>{
                    this.clientPop('suc', '数据保存成功')
                    location.reload()
                })
                .catch(()=>{
                    this.clientPop('err', '数据保存失败', ()=>{
                        this.scorllError()
                    })
                })
        },
        //处理参数后保存并提交
        setParmesOrStorage () {
            this.$refs['ruleForm'].validate(valid => {
                this.clearError('baseInfo')
                //验证基本信息
                if(valid) {
                    //验证结算明细
                    this.detailedErrorList = []
                    this.clearError('changeDetail')
                    const detailedErrorList = this.verificationDetailed()
                    if(detailedErrorList.length > 0) {
                        this.detailedErrorList = detailedErrorList
                        this.setError('changeDetail')
                        this.scorllError()
                        return
                    }

                    //验证服务费用
                    this.serviceErrorList = []
                    this.clearError('recommendedLessor')
                    const serviceErrorList = this.verificationService()
                    if(serviceErrorList.length > 0) {
                        this.serviceErrorList = serviceErrorList
                        this.setError('recommendedLessor')
                        this.scorllError()
                        return
                    }

                    //当业务类型为物资采购合同时判断是否已做动态评价
                    if(this.formData.businessTypeKey == 0) {
                        if(typeof this.formData.evaluate != 'number') {
                            this.$message.error('物资采购合同必须要先进行动态评价才能提交审核')
                            return
                        }
                    }

                    //所有验证通过后设置参数并发送接口
                    const paramsList = this.setParams ()
                    Promise.all(paramsList)
                        .then(()=>{
                            publicRequest.adoptIdObtainSubmitForReview(this.auditParams)
                                .then(()=>{
                                    this.clientPop('suc', '保存并提交成功', ()=>{
                                        this.printHandel()
                                    })
                                })
                                .catch(()=> {
                                    this.clientPop('err', '提交失败！')
                                })
                        })
                        .catch(()=>{
                            this.clientPop('err', '保存失败', ()=>{
                                this.scorllError()
                            })
                        })
                }else {
                    this.setError('baseInfo')
                    this.scorllError()
                }
            })
        },
        //验证结算明细
        verificationDetailed () {
            if(this.acceptanceData[0].children.length > 0) {
                const errList = new Set()
                const errTaget = [NaN, null, undefined, '']
                const errTagetLabel = [
                    { key: 'quantity', val: '结算数量不能为空' },
                    { key: 'taxExcludedAmount', val: '结算金额不能为空' },
                ]
                errTagetLabel.forEach(err=>{
                    this.acceptanceData[0].children.forEach(item=>{
                        if(errTaget.includes(item[err.key])) {
                            errList.add(err.val)
                        }
                    })
                })
                return Array.from(errList)
            }
            return ['请选择结算明细']
        },
        //验证服务费用
        verificationService () {
            if(this.tableDataService.length > 0) {
                const errList = new Set()
                const errTaget = [NaN, null, undefined, '']
                const errTagetLabel = [
                    { key: 'settlementUnitName', val: '请选择结算单位' },
                    { key: 'contractDtlName', val: '清单名称不能为空' },
                    { key: 'invoiceNo', val: '请填写发票编号' },
                    { key: 'quantity', val: '数量不能为空' },
                    { key: 'amount', val: '金额不能为空' },
                ]
                errTagetLabel.forEach(err=>{
                    this.tableDataService.forEach(item=>{
                        if(errTaget.includes(item[err.key])) {
                            errList.add(err.val)
                        }
                    })
                })
                return Array.from(errList)
            }
            return []
        },
        //删除
        deleteData () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                ()=>{
                    request.deletePurchaseSettlement({ billId: this.billId }
                    ).then(res=>{
                        if(res.code == 200) {
                            this.clientPop('suc', '删除成功', ()=>{
                                this.printHandel()
                            })
                        }
                    })
                }
            )
        },
        //刷新历史审核列表
        getAuditHistory () {
            publicRequest.adoptIdObtainGetAuditHistory(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //切换左侧菜单
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //操作成功后返回列表页面
        printHandel () {
            this.$router.replace('/purchaseSettlementList')
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x=>x === name)
            if(index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // elment表格事件
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        // elment表格事件
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
    },
}
// }
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}
.mainTitle {
    box-sizing: border-box;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246, 246, 246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
.errMessageBox {
    background-color: #fff;
}
.errMessage {
    margin-bottom: 0;
    color: red;
    font-size: 14px;
}

// ::v-deep input.el-input__inner {
//     border: 0;
// }
</style>
